package com.guokai2012.util;

import com.guokai2012.domain.LineData;
import com.qiniu.util.StringUtils;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

/**
 * @ClassName ListPanelItem
 * @Author JH012021
 * @Date 2021/8/12 16:54
 * @Description 主面板
 */
public class ListPanelItem2 extends JTabbedPane {
    private final SimpleDateFormat sdf;
    private final int emptyLine = 2;
    private final int lineHeight = 30;
    private final String timePlace = "可选择提醒时间...";
    private final String contextPlace = "提醒内容必填...";
    private List<LineData> dataList;
    private JPanel todoPanel;
    private final GridBagConstraints gbcH = new GridBagConstraints();
    private GridBagLayout glibly;

    public ListPanelItem2(List<LineData> data, String sdf) {
        this.sdf = new SimpleDateFormat(sdf);
        // 在水平方向填充
        gbcH.fill = GridBagConstraints.HORIZONTAL;
        gbcH.gridx = 0;
        gbcH.gridy = 0;
        gbcH.weightx = 1;
        gbcH.gridwidth = 3;
        this.dataList = data;
        initListPanelItem();
    }

    private void initListPanelItem() {
        this.todoPanel = new JPanel();
        this.glibly = new GridBagLayout();
        todoPanel.setLayout(glibly);
        JScrollPane scrollPane = new JScrollPane(todoPanel);

        addTab("待办事项", null, scrollPane);
        setMnemonicAt(0, KeyEvent.VK_1);
        addTab("已完成事项", null, null);
        setMnemonicAt(1, KeyEvent.VK_2);

        addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                updateTodoPanel();
            }
        });

        // 初始化数据
        int i = 0, size = dataList.size();
        for (; i < size; i++) {
            addLine(i, dataList.get(i));
        }

        // 初始化待输入行
        for (; i < size + emptyLine; i++) {
            addLine(i, new LineData());
        }

        gbcH.gridy = i;
        gbcH.weighty = 1;
        JPanel tmp = new JPanel();
        tmp.add(new JLabel("~我也是有底线的~", JLabel.CENTER));
        tmp.setName("ssssssss");
        todoPanel.add(tmp, gbcH, i);

        updateTodoPanel();
    }

    private void addLine(int key, LineData item) {
        gbcH.gridy = key;
        gbcH.weighty = 0;
        LinePanel panel = new LinePanel(key, item);
        todoPanel.add(panel, gbcH, key);
    }

    private void updateTodoPanel() {
        int sIn = getSelectedIndex();
        Component[] comps = todoPanel.getComponents();
        for (int i = 0; i < comps.length; i++) {
            boolean isVisible = true;
            if (comps[i] instanceof LinePanel) {
                LinePanel tmp = (LinePanel) comps[i];
                if (sIn == 1 && !tmp.checkBox.isSelected()) {
                    isVisible = false;
                } else if (sIn == 0 && tmp.checkBox.isSelected()) {
                    isVisible = false;
                }
                tmp.setVisible(isVisible);
            }
        }
    }

    private void addEmptyLine() {
        int pt = todoPanel.getComponentCount();
        System.out.println(pt);
        addLine(pt - 1, new LineData());
        gbcH.gridy = pt;
        gbcH.weighty = 1;
        Component component = todoPanel.getComponent(pt);
        System.out.println(component.getName());
        glibly.setConstraints(component, gbcH);
        todoPanel.updateUI();
    }

    /**
     * 行对象
     */
    private class LinePanel extends JPanel {
        private int key;
        private LineData item;
        private JCheckBox checkBox;
        private JTextField textField;
        private JTextField timeField;

        public LinePanel(int key, LineData item) {
            this.key = key;
            this.item = item;
            initLineData();
        }

        /**
         * 生成 行 组件
         */
        private void initLineData() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbcV = new GridBagConstraints();
            gbcV.fill = GridBagConstraints.HORIZONTAL;
            gbcV.gridy = 0;
            setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));

            // checkBox
            this.checkBox = new JCheckBox(null, null, item.getFinish());
            checkBox.setBackground(Color.WHITE);
            checkBox.setPreferredSize(new Dimension(30, lineHeight));
            gbcV.gridx = 0;
            gbcV.weightx = 0.0;
            add(checkBox, gbcV);
            checkBox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (StringUtils.isNullOrEmpty(textField.getText()) || contextPlace.equals(textField.getText())) {
                        checkBox.setSelected(false);
                        return;
                    }
                    commitSelect();
                }
            });

            // 提醒内容
            String tmpContext = contextPlace;
            if (null != item.getContext() && !"".equals(item.getContext())) {
                tmpContext = item.getContext();
            }
            this.textField = new JTextField(tmpContext);
            textField.setName("task");
            textField.setPreferredSize(new Dimension(200, lineHeight));
            textField.setBorder(null);
            gbcV.gridx = 1;
            gbcV.weightx = 1;
            textField.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    doPlaceholder((JTextField) e.getSource());
                }

                @Override
                public void focusLost(FocusEvent e) {
                    doPlaceholder((JTextField) e.getSource());
                    commit(false);
                }
            });
            add(textField, gbcV);

            // 提醒时间
            String tmpTime = timePlace;
            if (null != item.getTime()) {
                tmpTime = sdf.format(item.getTime());
            }
            this.timeField = new JTextField(tmpTime);
            timeField.setName("time");
            timeField.setPreferredSize(new Dimension(120, lineHeight));
            timeField.setBorder(null);

            gbcV.gridx = 3;
            gbcV.weightx = 0.0;
            add(timeField, gbcV);
            DateTimePicker dateTimePicker = new DateTimePicker(sdf.toPattern(), 200, 200);
            dateTimePicker.setTimeEnable(true).changeDateEvent(new Consumer<DateTimePicker>() {
                @Override
                public void accept(DateTimePicker o) {
                    commit(true);
                }
            }).register(timeField);
        }

        /**
         * 处理 placeholder
         */
        private void doPlaceholder(JTextField textField) {
            String text = textField.getText();
            String name = textField.getName();
            if (contextPlace.equals(text) || timePlace.equals(text)) {
                textField.setText(null);
            }
            if (null == text || StringUtils.isNullOrEmpty(text)) {
                if (name.equals("task")) {
                    textField.setText(contextPlace);
                } else {
                    textField.setText(timePlace);
                }
            }
        }

        /**
         * 设置 提醒日期超过后，字体颜色为红色
         */
        private void setForegroundColor() {
            if (item.getFinish()) {
                textField.setEnabled(false);
                timeField.setEnabled(false);
                textField.setForeground(Color.BLACK);
                timeField.setForeground(Color.BLACK);
                return;
            } else {
                textField.setEnabled(true);
                timeField.setEnabled(true);
            }
            Date time = item.getTime();
            if (null != time && System.currentTimeMillis() - (60 * 1000) > time.getTime()) {
                textField.setForeground(Color.RED);
                timeField.setForeground(Color.RED);
            } else if (null == time || System.currentTimeMillis() - (60 * 1000) <= time.getTime()) {
                textField.setForeground(Color.BLACK);
                timeField.setForeground(Color.BLACK);
            }
        }

        /**
         * 确认 数据
         */
        private void commit(boolean isNew) {
            String content = this.textField.getText();
            if (!StringUtils.isNullOrEmpty(content) && !contextPlace.equals(content)) {
                Date time = sdf.parse(this.timeField.getText(), new ParsePosition(0));
                if (isNew) {
                    this.item.setTime(time);
                    this.item.setRemindTime(time);
                } else {
                    if (key >= dataList.size()) {
                        LineData item = new LineData();
                        item.setContext(content);
                        item.setTime(time);
                        item.setRemindTime(time);
                        dataList.add(item);
                        addEmptyLine();
                    } else {
                        dataList.get(key).setRemindTime(time);
                        dataList.get(key).setTime(time);
                        dataList.get(key).setContext(content);
                    }
                }
            }
        }

        // 勾选完成、未完成
        private void commitSelect() {
            this.item.setFinish(this.checkBox.isSelected());
            if (this.checkBox.isSelected()) {
                this.item.setFinishTime(new Date());
            } else {
                this.item.setFinishTime(null);
            }
            updateTodoPanel();
        }
    }
}

